// ActionTraceDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ActionTrace.h"
#include "ActionTraceDlg.h"
#include "AnalyzeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

UINT MOUSE_UWM_HOOK = 0;
UINT KEYBOARD_UWM_HOOK = 0;
UINT UM_TRAYNOTIFICATION = WM_USER + 1;
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CActionTraceDlg dialog




CActionTraceDlg::CActionTraceDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CActionTraceDlg::IDD, pParent)
	, m_bTracing(false)
	, m_hLib(NULL)
	, m_hdc(NULL)
	, m_bMinOnTray(false)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	ZeroMemory(&m_sHookConf, sizeof(m_sHookConf));
}

void CActionTraceDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDB_TRACE, m_bnTrace);
	DDX_Control(pDX, IDC_STATIC_VERSION, m_staticVersion);
}

BEGIN_MESSAGE_MAP(CActionTraceDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_MESSAGE(UM_TRAYNOTIFICATION, &CActionTraceDlg::OnTrayNotification)
	ON_REGISTERED_MESSAGE(MOUSE_UWM_HOOK, &CActionTraceDlg::OnMouseHook)
	ON_REGISTERED_MESSAGE(KEYBOARD_UWM_HOOK, &CActionTraceDlg::OnKeyboardHook)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDB_TRACE, &CActionTraceDlg::OnBnClickedTrace)
	ON_BN_CLICKED(IDC_DISPLAY_REAL_TIME, &CActionTraceDlg::OnBnClickedDisplayRealTime)
	ON_BN_CLICKED(IDC_TRACK_MOUSE_MOVE, &CActionTraceDlg::OnBnClickedTrackMouseMove)
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_KEYUP_ONLY, &CActionTraceDlg::OnBnClickedKeyupOnly)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDB_ANALYZE, &CActionTraceDlg::OnBnClickedAnalyze)
	ON_BN_CLICKED(IDB_TO_TRAY, &CActionTraceDlg::OnBnClickedToTray)
END_MESSAGE_MAP()


// CActionTraceDlg message handlers

BOOL CActionTraceDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	::SetProp(m_hWnd, g_szPropName, g_hPropValue);

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	MOUSE_UWM_HOOK = RegisterWindowMessage(UWM_MOUSE_HOOK_MSG);
	KEYBOARD_UWM_HOOK = RegisterWindowMessage(UWM_KEYBOARD_HOOK_MSG);
	((CButton *)GetDlgItem(IDC_TRACK_MOUSE))->SetCheck(BST_CHECKED);
	((CButton *)GetDlgItem(IDC_TRACK_KEYBOARD))->SetCheck(BST_CHECKED);
	((CButton *)GetDlgItem(IDC_DISPLAY_REAL_TIME))->SetCheck(BST_CHECKED);
	((CButton *)GetDlgItem(IDC_TRACK_MOUSE_MOVE))->SetCheck(BST_CHECKED);
	((CButton *)GetDlgItem(IDC_KEYUP_ONLY))->SetCheck(BST_CHECKED);
	((CButton *)GetDlgItem(IDC_STAY_ON_TRAY))->SetCheck(BST_CHECKED);

	m_sNotifyData.cbSize = sizeof(NOTIFYICONDATA);
	m_sNotifyData.hWnd = this->m_hWnd;
	m_sNotifyData.uID = IDR_TRAYMENU;
	lstrcpy(m_sNotifyData.szTip, _T("Action Trace: Not Tracing"));
	m_sNotifyData.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
	m_sNotifyData.hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_sNotifyData.uCallbackMessage = UM_TRAYNOTIFICATION;
	Shell_NotifyIcon(NIM_ADD, &m_sNotifyData);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CActionTraceDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CActionTraceDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CActionTraceDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CActionTraceDlg::OnBnClickedTrace()
{
	if (m_bTracing)
	{
		UninstallHook uninstall = (UninstallHook)GetProcAddress(m_hLib, "UninstallHook");
		BOOL ret = uninstall();
		lstrcpy(m_sNotifyData.szTip, _T("Action Trace: Not Tracing"));
		Shell_NotifyIcon(NIM_MODIFY, &m_sNotifyData);

		if (FreeLibrary(m_hLib) == NULL)
		{
			MessageBox(_T("Free lib failed!"));
			return;
		}
		m_hLib = NULL;

		GetDlgItem(IDC_TRACK_MOUSE)->EnableWindow(TRUE);
		GetDlgItem(IDC_TRACK_KEYBOARD)->EnableWindow(TRUE);
		if (m_hdc)
		{
			::ReleaseDC(NULL, m_hdc);
			m_hdc = NULL;
		}
		m_bnTrace.SetWindowText(_T("&Trace"));
		m_bTracing = false;
	}
	else
	{
		m_hLib = LoadLibrary(_T("Hook.dll"));
		if (m_hLib == NULL)
		{
			DWORD err = GetLastError();
			CString str;
			str.AppendFormat(_T("%d"), err);
			SetWindowText(str.GetString());
			MessageBox(_T("To make sure you have permission to write in log directory!"));
			return;
		}

		//HookConf conf = {NULL};
		m_sHookConf.isHookMouse = (((CButton *)GetDlgItem(IDC_TRACK_MOUSE))->GetCheck() == BST_CHECKED? TRUE : FALSE);
		m_sHookConf.isHookKeyboard = (((CButton *)GetDlgItem(IDC_TRACK_KEYBOARD))->GetCheck() == BST_CHECKED? TRUE : FALSE);
		m_sHookConf.isNotifyServer = (((CButton *)GetDlgItem(IDC_DISPLAY_REAL_TIME))->GetCheck() == BST_CHECKED? TRUE : FALSE);
		m_sHookConf.isTrackMouseMove = (((CButton *)GetDlgItem(IDC_TRACK_MOUSE_MOVE))->GetCheck() == BST_CHECKED? TRUE : FALSE);
		m_sHookConf.isKeyUpOnly = (((CButton *)GetDlgItem(IDC_KEYUP_ONLY))->GetCheck() == BST_CHECKED? TRUE : FALSE);
		//m_sHookConf.isLogText = TRUE;
		if (m_sHookConf.isHookKeyboard == FALSE && m_sHookConf.isHookMouse == FALSE)
		{
			MessageBox(_T("Please set one Tracker at least."));
			return;
		}

		SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
		setconf(&m_sHookConf);
		InstallHook install = (InstallHook)GetProcAddress(m_hLib, "InstallHook");
		if (install == NULL || install(AfxGetMainWnd()->GetSafeHwnd()) == NULL)
		{
			FreeLibrary(m_hLib);
			MessageBox(_T("Hook failed!"));
			return;
		}
		lstrcpy(m_sNotifyData.szTip, _T("Action Trace: Tracing"));
		Shell_NotifyIcon(NIM_MODIFY, &m_sNotifyData);

		GetDlgItem(IDC_TRACK_MOUSE)->EnableWindow(FALSE);
		GetDlgItem(IDC_TRACK_KEYBOARD)->EnableWindow(FALSE);
		m_hdc = ::GetDC(NULL);
		::SetROP2(m_hdc, R2_WHITE);
		m_bnTrace.SetWindowText(_T("&Stop"));
		m_bTracing = true;
	}
}

static TCHAR buf[256] = {NULL};
LRESULT CActionTraceDlg::OnMouseHook(WPARAM wParam, LPARAM lParam)
{
	ZeroMemory(buf, 256);
	_stprintf(buf, _T("Mouse %d: x=%d, y=%d"), wParam, LOWORD(lParam), HIWORD(lParam));

	SetWindowText(buf);
	//if (m_hdc)
	//	TextOut(m_hdc, 0, 0, buf, lstrlen(buf));
	return 0L;
}

LRESULT CActionTraceDlg::OnKeyboardHook(WPARAM wParam, LPARAM lParam)
{
	ZeroMemory(buf, 256);
	_stprintf(buf, _T("Key %d: count=%d%s"), wParam, lParam&0xF, (lParam&0x20000000 == 0)?_T("") : _T(", Alt Pressed"));

	SetWindowText(buf);
	//if (m_hdc)
	//	TextOut(m_hdc, 0, 0, buf, lstrlen(buf));
	return 0L;
}

LRESULT CActionTraceDlg::OnTrayNotification(WPARAM wParam, LPARAM lParam)
{
	if (wParam != m_sNotifyData.uID || (lParam != WM_LBUTTONUP && lParam != WM_RBUTTONUP))
		return 0;

	CMenu menu;
	if (!menu.LoadMenu(wParam))
		return 0;
	CMenu *pSubMenu = menu.GetSubMenu(0);
	if (!pSubMenu)
		return 0;

	if (lParam == WM_RBUTTONUP)
	{
		::SetMenuDefaultItem(pSubMenu->m_hMenu, 0, TRUE);
		CPoint mouse;
		GetCursorPos(&mouse);
		if (m_bTracing)
			pSubMenu->ModifyMenu(IDM_TOGGLE, MF_BYCOMMAND | MF_STRING, IDM_TOGGLE, _T("&Stop"));
		else
			pSubMenu->ModifyMenu(IDM_TOGGLE, MF_BYCOMMAND | MF_STRING, IDM_TOGGLE, _T("&Trace"));

		::SetForegroundWindow(m_sNotifyData.hWnd);
		::TrackPopupMenu(pSubMenu->m_hMenu, 0, mouse.x, mouse.y, 0, m_sNotifyData.hWnd, NULL);
	}
	else
	{
		ShowWindow(SW_SHOW);
		if (m_sHookConf.isNotifyServer && m_hLib)
		{
			SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
			setconf(&m_sHookConf);
		}
	}
	return 1;
}

void CActionTraceDlg::OnBnClickedDisplayRealTime()
{
	if (!m_bTracing)
		return;

	m_sHookConf.isNotifyServer = (((CButton *)GetDlgItem(IDC_DISPLAY_REAL_TIME))->GetCheck() == BST_CHECKED? TRUE : FALSE);
	SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
	setconf(&m_sHookConf);
}

void CActionTraceDlg::OnBnClickedTrackMouseMove()
{
	if (!m_bTracing)
		return;

	m_sHookConf.isTrackMouseMove = (((CButton *)GetDlgItem(IDC_TRACK_MOUSE_MOVE))->GetCheck() == BST_CHECKED? TRUE : FALSE);
	SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
	setconf(&m_sHookConf);
}

void CActionTraceDlg::OnBnClickedKeyupOnly()
{
	if (!m_bTracing)
		return;

	m_sHookConf.isKeyUpOnly = (((CButton *)GetDlgItem(IDC_KEYUP_ONLY))->GetCheck() == BST_CHECKED? TRUE : FALSE);
	SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
	setconf(&m_sHookConf);
}

BOOL CActionTraceDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
	switch(LOWORD(wParam))
	{
	case IDM_TOGGLE:
		OnBnClickedTrace();
		break;
	case IDM_ANALYZE:
		OnBnClickedAnalyze();
		break;
	case IDM_ABOUTBOX:
		OnSysCommand(IDM_ABOUTBOX, 0);
		break;
	case IDM_EXIT:
		return DestroyWindow();
		break;
	default:
		return CDialog::OnCommand(wParam, lParam);
	}
}

void CActionTraceDlg::OnClose()
{
	BOOL minWhenClose = (((CButton *)GetDlgItem(IDC_STAY_ON_TRAY))->GetCheck() == BST_CHECKED? TRUE : FALSE);
	if (minWhenClose)
	{
		ShowWindow(SW_HIDE);
		if (m_sHookConf.isNotifyServer && m_hLib)
		{
			m_sHookConf.isNotifyServer = FALSE;
			SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
			setconf(&m_sHookConf);
			m_sHookConf.isNotifyServer = TRUE;
		}
		return;
	}

	CDialog::OnClose();
}

void CActionTraceDlg::OnDestroy()
{
	CDialog::OnDestroy();

	if (m_bTracing && m_hLib != NULL)
	{
		UninstallHook uninstall = (UninstallHook)GetProcAddress(m_hLib, "UninstallHook");
		BOOL ret = uninstall();

		if (FreeLibrary(m_hLib) == NULL)
		{
			MessageBox(_T("Free lib failed!"));
			return;
		}

		if(m_hdc)
			::ReleaseDC(NULL, m_hdc);
	}

	Shell_NotifyIcon(NIM_DELETE, &m_sNotifyData);
}

void CActionTraceDlg::OnBnClickedAnalyze()
{
	CAnalyzeDlg dlg;
	dlg.SetRecPath(m_sHookConf.logFile);
	dlg.DoModal();
}

void CActionTraceDlg::OnBnClickedToTray()
{
	ShowWindow(SW_HIDE);
	if (m_sHookConf.isNotifyServer && m_hLib)
	{
		m_sHookConf.isNotifyServer = FALSE;
		SetConf setconf = (SetConf)(GetProcAddress(m_hLib, "SetConf"));
		setconf(&m_sHookConf);
		m_sHookConf.isNotifyServer = TRUE;
	}
}
